package com.emmy.walnut.app;

import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.db.SupportSQLiteOpenHelper;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.DatabaseConfiguration;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.support.annotation.NonNull;

import com.emmy.walnut.constant.AppConstant;
import com.emmy.walnut.dao.LabelDao;
import com.emmy.walnut.dao.RecordDao;
import com.emmy.walnut.dao.UserDao;
import com.emmy.walnut.model.Label;
import com.emmy.walnut.model.Record;
import com.emmy.walnut.model.User;
import com.emmy.walnut.util.MD5Util;

/**
 * @ClassName AppDatabase
 * @Description TODO
 * @Author zhouxuan
 * @Date 2020/02/04 12:26
 * @Version 1.0
 */
@Database(entities = {User.class, Label.class, Record.class}, version = 3)
//每次创建AppDatabase的开销比较大，所以应该设计成单例模式
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;
    public abstract UserDao userDao();
    public abstract LabelDao labelDao();
    public abstract RecordDao recordDao();

    private static Migration MIGRATION_2;
    private static Migration MIGRATION_3;

    static {
        MIGRATION_2 = new Migration(1, 2) {
            @Override
            public void migrate(@NonNull SupportSQLiteDatabase database) {
                database.execSQL("alter table user add avatar varchar(40)");
            }
        };

        MIGRATION_3 = new Migration(2, 3) {
            @Override
            public void migrate(@NonNull SupportSQLiteDatabase database) {
                database.execSQL("update user set username = 'emmyzhou' " +
                        "where username = '12345678'");
            }
        };

        INSTANCE = Room.databaseBuilder(AppConstant.APPLICATION_CONTEXT,
                AppDatabase.class, "walnut.db").
                addMigrations(MIGRATION_2).addMigrations(MIGRATION_3).build();
    }

    public static AppDatabase getInstance() {
        return INSTANCE;
    }

    @Override
    protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration config) {
        return null;
    }
}
